package com.agy.filemanager.controller;

import com.agy.filemanager.configuration.MyInterceptor;
import com.agy.filemanager.entity.DcBaseMenu;
import com.agy.filemanager.entity.DcManagerInfo;
import com.agy.filemanager.entity.DcViewSystemUsers;
import com.agy.filemanager.entity.SessionInfo;
import com.agy.filemanager.service.DcLoginInfoService;
import com.agy.filemanager.toolClass.Base64Util;
import com.agy.filemanager.toolClass.DigestUtil;
import com.agy.filemanager.toolClass.Result;
import com.agy.filemanager.toolClass.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.util.List;
import java.util.UUID;

/**
 * 登陆、注册页面控制器
 * @author jpf
 */
@Slf4j
@Controller
@RequestMapping(value="/login")
public class LoginController {

    @Autowired
    private DcLoginInfoService dcLoginInfoService;
    /**
     * 登陆页面
     * @return  landingPage.ftl 登陆页
     */
    @GetMapping("/landingPage")
    public String doView01(){
        return "loginFile/landingPage";
    }

    /**
     * 首页面
     * @param info     session实体
     * @param model
     * @return  homePage.ftl
     */
    @GetMapping("/home")
    public String doView02(@SessionAttribute(MyInterceptor.SESSION_KEY) SessionInfo info, Model model){
        model.addAttribute("name", info.getName());
        switch (info.getSign()){
            case "0":
                model.addAttribute("unit", " 系统管理员");
                //TODO:jpf-系统管理员默认具有所有权限
                List<DcBaseMenu> menuList = this.dcLoginInfoService.selectMenusByUser();
                model.addAttribute("menuList", menuList);
                break;
            case "1":
                model.addAttribute("unit", "安工院");
                model.addAttribute("menuList", new DcBaseMenu());
                break;
            case "2":
                model.addAttribute("unit", "中石化");
                model.addAttribute("menuList", new DcBaseMenu());
                break;
            case "3":
                model.addAttribute("unit", "服务企业");
                model.addAttribute("menuList", new DcBaseMenu());
                break;
            default:
                break;
        }
        return "loginFile/homePage";
    }

    /**
     * 登陆验证
     * @param session     session
     * @return  map
     */
    @PostMapping("/loginPost")
    @ResponseBody
    public Result loginPost(@RequestBody DcViewSystemUsers entity, HttpSession session) {
        //base64解密
        String account = Base64Util.decode(entity.getAccount());
        String password = Base64Util.decode(entity.getPwd());
        //根据用户名和用户性质获取用户信息
        DcViewSystemUsers userinfo = this.dcLoginInfoService.selectByAccount(account,entity.getSign());
        if(userinfo == null || password == null){
            return ResultUtil.error("无效的用户名或密码");
        }else{
            String psw = DigestUtil.sha256Digest(password + userinfo.getSalt());
            if (!userinfo.getPwd().equals(psw)) {
                return ResultUtil.error("无效的用户名或密码");
            }
            //存储session信息
            SessionInfo info = new SessionInfo();
            info.setId(userinfo.getId());
            info.setAccount(userinfo.getAccount());
            info.setName(userinfo.getName());
            info.setPhone(userinfo.getPhone());
            info.setEmail(userinfo.getEmail());
            info.setSign(userinfo.getSign());
            // 设置session
            session.setAttribute(MyInterceptor.SESSION_KEY, info);
        }
        return ResultUtil.success(null,"登陆成功");
    }

    /**
     * 注销登陆，移除session
     * @param session
     * @return  landingPage.ftl 重定向登陆页面
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 移除session
        session.removeAttribute(MyInterceptor.SESSION_KEY);
        return "redirect:/login/landingPage";
    }
    /**
     * 注册页面
     * @return  registerPage.ftl 登陆页
     */
    @GetMapping("/registerPage")
    public String doView03(){
        return "loginFile/registerPage";
    }

    /**
     * 注册页面-提交注册信息
     * @param entity @RequestBody接收json字符串，不能省略
     * @return
     */
    @PostMapping("/registerSubmit")
    @ResponseBody
    public Result registerSubmit(@RequestBody DcManagerInfo entity){
        try{
            entity.setId(UUID.randomUUID().toString().replace("-",""));
            String salt = UUID.randomUUID().toString();
            //用UUID生成随机盐,将salt和password一起保存到数据库里
            entity.setPwd(DigestUtil.sha256Digest(entity.getPwd() + salt));
            entity.setSalt(salt);
            entity.setCreated(new Date(System.currentTimeMillis()));// new Date()为获取当前系统时间
            entity.setUpdated(new Date(System.currentTimeMillis()));
            entity.setType(new Byte("1"));
            this.dcLoginInfoService.insertUser(entity);
            return ResultUtil.success(null,"注册成功");
        }catch(Exception ex){
            log.error("pos:login/registerSubmit");
            return ResultUtil.error("注册失败");
        }
    }

    /**
     * 判断用户名是否有效
     * @param account
     * @return
     */
    @PostMapping("/usernameEffective")
    @ResponseBody
    public Result usernameEffective(@RequestParam String account,@RequestParam String sign){
        account = Base64Util.decode(account);
        sign = Base64Util.decode(sign);
        DcViewSystemUsers userinfo = this.dcLoginInfoService.selectByAccount(account,sign);
        if(userinfo != null){
            return ResultUtil.error("用户名已存在");
        }
        return ResultUtil.success(null,"用户名有效");
    }
}
